package com.wande.dataplatform.config;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Doris 数据源配置
 * 
 * @author ruoyi
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "doris", name = "jdbc-url")
public class DorisDataSourceConfig {

    private final DorisProperties dorisProperties;

    /**
     * 创建 Doris 数据源连接池
     * 
     * @return Doris 数据源
     */
    @Bean(name = "dorisDataSource")
    public DataSource dorisDataSource() {
        log.info("初始化 Doris 数据源连接池");
        
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(dorisProperties.getJdbcUrl());
        config.setUsername(dorisProperties.getUsername());
        config.setPassword(dorisProperties.getPassword());
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        
        // 连接池配置
        config.setMaximumPoolSize(dorisProperties.getMaxPoolSize());
        config.setMinimumIdle(dorisProperties.getMinIdle());
        config.setConnectionTimeout(dorisProperties.getConnectionTimeout());
        config.setIdleTimeout(600000); // 10分钟
        config.setMaxLifetime(1800000); // 30分钟
        
        // 连接测试配置
        config.setConnectionTestQuery("SELECT 1");
        config.setValidationTimeout(3000);
        
        // 连接池名称
        config.setPoolName("DorisHikariPool");
        
        // 性能优化配置
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.addDataSourceProperty("useServerPrepStmts", "true");
        config.addDataSourceProperty("useLocalSessionState", "true");
        config.addDataSourceProperty("rewriteBatchedStatements", "true");
        config.addDataSourceProperty("cacheResultSetMetadata", "true");
        config.addDataSourceProperty("cacheServerConfiguration", "true");
        config.addDataSourceProperty("elideSetAutoCommits", "true");
        config.addDataSourceProperty("maintainTimeStats", "false");
        
        log.info("Doris 数据源连接池初始化完成: {}", dorisProperties.getJdbcUrl());
        
        return new HikariDataSource(config);
    }

}
